package com.guoxue.action.front.pay;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.action.front.BaseAction;
import com.guoxue.domain.CoinsVo;
import com.guoxue.domain.RechargeVo;
import com.guoxue.domain.UserCoinsVo;
import com.guoxue.pay.wx.util.CommonUtil;
import com.guoxue.pay.wx.util.ConfigUtil;
import com.guoxue.pay.wx.util.MyWXSignUtil;
import com.guoxue.pay.wx.util.PayCommonUtil;
import com.guoxue.pay.wx.util.SignUtil;
import com.guoxue.pay.wx.util.XMLUtil;
import com.guoxue.service.ICoinsService;
import com.guoxue.service.IRechargeService;
import com.guoxue.service.IUserCoinsService;
import com.guoxue.util.JsonUtil;
import com.guoxue.util.OtherUtils;

@Controller
@RequestMapping(value = "/pay")
public class WXPayAction extends BaseAction {

	@Resource
	private IUserCoinsService userCoinsService;
	@Resource
	private ICoinsService coinsService;
	@Resource
	private IRechargeService rechargeService;
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param coinsId 金币id
	 * @param count 数量
	 * @param uid 用户id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getWXOrderInfo")
	public JSON getOrderInfo(HttpServletRequest req, HttpServletResponse resp, Integer coinsId, Integer count,
			Integer uid) {
		try {
			if (coinsId == null) {
				return Message(ERROR, "未提交商品id", null);
			}
			if (count == null) {
				return Message(ERROR, "未提交商品数量", null);
			}
			if (count <= 0) {
				return Message(ERROR, "商品数量不能为0或者负数", null);
			}
			if(count > 1 ){
				return Message(ERROR, "商品数量超过限制数量", null);
			}
			if (null == uid) {
				return Message(ERROR, "未提交用户id", null);
			}
			CoinsVo coinsVo = coinsService.getCoinsById(coinsId);
			if(null == coinsVo){
				return Message(ERROR, "该商品不存在", null);
			}
			Integer price = coinsVo.getPrice();
			Integer totalMoney = count * price;
			RechargeVo recharge = new RechargeVo();
			recharge.setCoinsId(coinsId);
			recharge.setCount(count);
			recharge.setuId(uid);
			recharge.setPayMoney(totalMoney);
			recharge.setPayStatus("1");
			recharge.setPayWay("2");
			String aa = OtherUtils.getCurrentDateNum();
		    int bb = (new Random().nextInt(9999-1000+1)+1000);
			String outTradeNo = aa+bb;
			recharge.setOutTradeNo(outTradeNo);
			recharge.setCreateTime(OtherUtils.getCurrentDate());
			rechargeService.saveRecharge(recharge);
			JSONObject signUrl = generateOrderInfoByWeiXinPay(outTradeNo,Float.valueOf(totalMoney.toString()), req, resp);
			if (signUrl.size() > 0) {
				return Message(SUCCESS, "WX订单创建成功", signUrl);
			} else {
				return Message(ERROR, "WX订单创建失败", null);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return Message(ERROR, "WX订单创建失败", null);
		}
	}

	/**
	 * 微信支付
	 * 
	 * @param orderId
	 *            订单编号
	 * @param actualPay
	 *            实际支付金额
	 * @return 
	 */
	private JSONObject generateOrderInfoByWeiXinPay(String orderId, float actualPay, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String notify_url = ConfigUtil.NOTIFY_URL;// 回调地址
		String uuid = UUID.randomUUID().toString().substring(0, 8);
		System.out.print("uuid" + uuid);
		//金额转化为分为单位
		String finalmoney = String.format("%.2f", actualPay);
		finalmoney = finalmoney.replace(".", "");
		System.out.println(finalmoney);
		SortedMap<String, String> signParams = new TreeMap<String, String>();
		signParams.put("appid", ConfigUtil.APP_ID);// app_id
		signParams.put("body", "测试");// 商品参数信息
		signParams.put("mch_id", ConfigUtil.MCH_ID);// 微信商户账号
		signParams.put("nonce_str", uuid);// 32位不重复的编号
		signParams.put("notify_url", notify_url);// 回调页面
		signParams.put("out_trade_no", orderId);// 订单编号
		signParams.put("spbill_create_ip", request.getRemoteAddr());// 请求的实际ip地址
		//signParams.put("total_fee", finalmoney);// 支付金额 单位为分
		signParams.put("total_fee", "1");// 支付金额 单位为分
		signParams.put("trade_type", "APP");// 付款类型为APP
		String sign = PayCommonUtil.createSign2("UTF-8", signParams);// 生成签名
		signParams.put("sign", sign);
		signParams.remove("key");// 调用统一下单无需key（商户应用密钥）
		String requestXml = PayCommonUtil.getRequestXml2(signParams);// 生成Xml格式的字符串
		System.out.println(requestXml);
		String result = CommonUtil.httpsRequest2(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXml);// 以post请求的方式调用统一下单接口
		System.out.println(result);
		Map map = XMLUtil.doXMLParse(result);
		String return_code = (String) map.get("return_code");
		System.out.println(return_code);
		String prepay_id = null;
		if (return_code.contains("SUCCESS")) {
			prepay_id = (String) map.get("prepay_id");// 获取到prepay_id
			StringBuffer weiXinSb = new StringBuffer();
			String uuid2 = UUID.randomUUID().toString().substring(0, 8);
			long currentTimeMillis = System.currentTimeMillis();// 生成时间戳
			long second = currentTimeMillis / 1000L;// （转换成秒）
			String seconds = String.valueOf(second).substring(0, 10);// （截取前10位）
			SortedMap<String, String> signParam = new TreeMap<String, String>();
			signParam.put("appid", ConfigUtil.APP_ID);// app_id
			signParam.put("partnerid", ConfigUtil.MCH_ID);// 微信商户账号
			signParam.put("prepayid", prepay_id);// 预付订单id
			signParam.put("package", "Sign=WXPay");// 默认sign=WXPay
			signParam.put("noncestr", uuid2);// 自定义不重复的长度不长于32位
			signParam.put("timestamp", seconds);// 北京时间时间戳
			String signAgain = PayCommonUtil.createSign2("UTF-8", signParam);// 再次生成签名
			signParams.put("sign", signAgain);
			weiXinSb.append("appid=").append(ConfigUtil.APP_ID).append("&partnerid=").append(ConfigUtil.MCH_ID)
					.append("&prepayid=").append(prepay_id).append("&package=Sign=WXPay").append("&noncestr=")
					.append(uuid).append("&timestamp=").append(seconds).append("&sign=").append(signAgain);// 拼接参数返回给移动端
			System.out.println(weiXinSb.toString());
			
			json.put("appid", ConfigUtil.APP_ID);
			json.put("partnerid", ConfigUtil.MCH_ID);
			json.put("prepayid", prepay_id);
			json.put("package", "Sign=WXPay");
			json.put("noncestr", uuid);
			json.put("timestamp", seconds);
			json.put("sign", signAgain);
			return json;
		} else {
			return json;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/callBackWXPay")
	public JSON callBackWXPay(HttpServletRequest req, HttpServletResponse resp) {
		try {
			BufferedReader reader = req.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			String  xmlString = inputString.toString();
			System.out.println("----[微信回调]接收到的报文---" + xmlString);
			 if(!StringUtils.isEmpty(inputString.toString())){
				 //Map<String, String> map = new HashMap<String, String>();
				 	Map map = XMLUtil.doXMLParse(xmlString);
			        String result_code = "";
			        String out_trade_no = "";
			        result_code = (String) map.get("result_code");
			        System.out.println("result_code"+result_code);
			        out_trade_no = (String) map.get("out_trade_no");
			        System.out.println("out_trade_no"+out_trade_no);
			        String transactionId  = (String) map.get("transaction_id");
			        System.out.println("transactionId"+transactionId);
			        String total_fee  = (String) map.get("total_fee");
			        System.out.println("total_fee"+total_fee);
			        if (MyWXSignUtil.checkSign(xmlString)) {
			        	RechargeVo recharge = rechargeService.getRecharge(out_trade_no);
						if(null == recharge){
							return Message(ERROR, "WX支付失败", PayCommonUtil.setXML(result_code,"FAIL"));
						}
						System.out.println("WX:"+recharge.getPayStatus().equals("1"));
						System.out.println("WX:"+recharge.getPayStatus().equals(1));
						if(recharge.getPayStatus().equals("1")){
							//2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
							String payMoney = String.valueOf(recharge.getPayMoney());
							System.out.println("WX支付金额"+payMoney);
							//金额转化为分为单位
							float sessionmoney = Float.parseFloat(payMoney);
							String finalmoney = String.format("%.2f", sessionmoney);
							finalmoney = finalmoney.replace(".", "");
							//float totalFee = Float.parseFloat(total_fee);
							//String finalmoney_totalFee = String.format("%.2f", totalFee);
							//finalmoney_totalFee = finalmoney_totalFee.replace(".", "");
							System.out.println("finalmoney_totalFee"+total_fee);
							System.out.println("finalmoney"+finalmoney);
							/*if(!finalmoney.equals(total_fee)){
								return Message(ERROR, "WX支付失败", PayCommonUtil.setXML(result_code,"FAIL"));
							}*/
							recharge.setPayStatus("2");
							recharge.setTradeNo(transactionId);
							rechargeService.saveRecharge(recharge);
							System.out.println("更新订单状态和加入微信订单号");
							UserCoinsVo userCoinsVo = userCoinsService.getUserCoinsById(recharge.getuId());
							if(null == userCoinsVo){
								userCoinsVo = new UserCoinsVo();
								userCoinsVo.setUid(recharge.getuId());
								CoinsVo coinsVo = coinsService.getCoinsById(recharge.getCoinsId());
								System.out.println("WXPay增加前金币无记录"+userCoinsVo.getCoinsNumber());
								Integer coinsNumber = coinsVo.getValue() * recharge.getCount()+coinsVo.getGiveCoins();
								System.out.println("WXPay增加金币无记录"+coinsNumber);
								userCoinsVo.setCoinsNumber(coinsNumber);
								System.out.println("WXPay增加后金币无记录"+userCoinsVo.getCoinsNumber());
								userCoinsService.saveUserCoins(userCoinsVo);
							}else{
								CoinsVo coinsVo = coinsService.getCoinsById(recharge.getCoinsId());
								System.out.println("WXPay增加前金币有记录"+userCoinsVo.getCoinsNumber());
								Integer coinsNumber = coinsVo.getValue() * recharge.getCount()+coinsVo.getGiveCoins();
								System.out.println("WXPay增加金币有记录"+userCoinsVo.getCoinsNumber());
								userCoinsVo.setCoinsNumber(userCoinsVo.getCoinsNumber()+coinsNumber);
								System.out.println("WXPay增加后金币有记录"+userCoinsVo.getCoinsNumber());
								userCoinsService.saveUserCoins(userCoinsVo);
							}
								System.out.println("WXPay更新用户金币数量");
								resp.getWriter().append(PayCommonUtil.setXML("SUCCESS","OK"));
								return Message(SUCCESS, "WX支付成功", PayCommonUtil.setXML("SUCCESS","OK"));
						}else{
							resp.getWriter().append(PayCommonUtil.setXML("SUCCESS","OK"));
							return Message(SUCCESS, "WX支付成功", PayCommonUtil.setXML("SUCCESS","OK"));
						}
			        } else {
			        	return Message(ERROR, "WX支付失败", PayCommonUtil.setXML(result_code,"FAIL"));
			        }
			 }else{
				 return Message(ERROR, "未获取到微信返回的结果", null);
			 }
		} catch (Exception e) {
			e.printStackTrace();
			return Message(ERROR, "WX支付失败", null);
		}
	}
	
	
	
}
